from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Enum, JSON
from sqlalchemy.orm import declarative_base, relationship
import enum
import datetime

Base = declarative_base()

class SenderEnum(str, enum.Enum):
    user = "user"
    ai = "ai"

class ContentTypeEnum(str, enum.Enum):
    text = "text"
    image = "image"
    mixed = "mixed"

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(64), unique=True, nullable=False, index=True)
    email = Column(String(255), unique=True, nullable=True, index=True)
    password = Column(String(255), nullable=False)
    created_at = Column(DateTime, default=datetime.datetime.utcnow)

class Conversation(Base):
    __tablename__ = "conversations"
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    name = Column(String(255), nullable=True)
    created_at = Column(DateTime, default=datetime.datetime.utcnow)
    user = relationship("User")

class Message(Base):
    __tablename__ = "messages"
    id = Column(Integer, primary_key=True, index=True)
    conversation_id = Column(Integer, ForeignKey("conversations.id"), nullable=False)
    sender = Column(Enum(SenderEnum), nullable=False)
    content_type = Column(Enum(ContentTypeEnum), nullable=False)
    content = Column(String(65535), nullable=True)
    oss_urls = Column(JSON, nullable=True)
    created_at = Column(DateTime, default=datetime.datetime.utcnow)
    conversation = relationship("Conversation")

class DetectionResult(Base):
    __tablename__ = "detection_results"
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, index=True)
    title = Column(String(255))
    oss_url = Column(String(1024))
    message = Column(String(1024))

class ResultGroup(Base):
    __tablename__ = "result_groups"
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    title = Column(String(255), nullable=False)
    created_at = Column(DateTime, default=datetime.datetime.utcnow)
    items = relationship("ResultItem", back_populates="group")

class ResultItem(Base):
    __tablename__ = "result_items"
    id = Column(Integer, primary_key=True, index=True)
    group_id = Column(Integer, ForeignKey("result_groups.id"), nullable=False)
    oss_url = Column(String(255), nullable=False)
    detection_info = Column(JSON)
    created_at = Column(DateTime, default=datetime.datetime.utcnow)
    group = relationship("ResultGroup", back_populates="items") 